import {
  ArgumentsHost,
  BadRequestException,
  Catch,
  ExceptionFilter,
  ForbiddenException,
  NotFoundException,
} from '@nestjs/common';
import { Response } from 'express';
import { Exception } from './utils/exception';

// 统一处理错误情况
@Catch()
export class AppFilter<T> implements ExceptionFilter {
  catch(exception: T, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const res = ctx.getResponse<Response>();
    // 找不到接口的资源的情况不打印
    if (exception instanceof NotFoundException) {
      res.send({
        code: 404,
        message: '无资源',
        data: null,
      });
      return;
    }
    // 参数校验错误
    if (exception instanceof BadRequestException) {
      const response = exception.getResponse();
      res.send({
        code: 400,
        message: response,
        data: null,
      });
      return;
    }
    // 守卫拦截
    if (exception instanceof ForbiddenException) {
      res.send({
        code: 403,
        message: '无权限',
        data: null,
      });
      return;
    }
    // 业务异常
    if (exception instanceof Exception) {
      res.send({
        code: exception.cause ? exception.cause : 200,
        message: exception.message,
        data: null,
      });
      return;
    }
    console.log(exception);
    res.send({
      code: 500,
      message: '服务器发生错误',
      data: null,
    });
  }
}
